// 通过 node 开启一个中控服务器，用于定时刷新小程序调用接口的凭证

const express = require("express");
const http = require("axios");
const config = require("@conf/config").appConfig;
const app = express();
const _ = require("./../db/query");

let nexTime = 0;
let timer;
let expires = 0;
let access_token = '';

function refreshAccessToken(fn, time) {
  const refreshToken = function() {
    fn(refreshToken)
  }
  timer = setTimeout(refreshToken, time);
}

function getAccessToken(cb) {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }

  // 获取 access_token
  http({
    // url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET",
    url: "https://api.weixin.qq.com/cgi-bin/token",
    method: 'GET',
    params: {
      grant_type: "client_credential",
      appid: config.appid,
      secret: config.secret,
    }
  }).then(res => {
    if (res.data.access_token) {
      const { access_token, expires_in } = res.data || {};
      return _.query('select count(*) as count from access')
    }
  }).then(res => {
    const { count } =res[0] || {};
    if (count === 0) {
      return _.query('insert into access set ?', {
        token: access_token,
        expires,
      })
    } else {
      return _.query('update access set ?', {
        token: access_token,
        expires,
      })
    }
  }).then(res => {
    if (res) {
      nexTime = (expires || 7200) *1000 // s
      setTimeout(cb, nexTime)
    }
  }).catch(err => {
    console.log('error is:', err);
    nexTime = 30 * 1000;
    timer = setTimeout(cb, nexTime)
  })
} 

refreshAccessToken(getAccessToken, 0);

module.exports = app